package com.miui.theme.custom.screen

import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.miui.theme.custom.components.AppTopAppBar
import com.miui.theme.custom.navigation.currentComposeNavigator
import com.miui.theme.custom.viewmodel.ColumnDefinition
import com.miui.theme.custom.viewmodel.CreateTableViewModel
import com.miui.theme.custom.viewmodel.DataState
import com.miui.theme.custom.viewmodel.supportedDataTypes
import org.koin.androidx.compose.koinViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateTableScreen(viewModel: CreateTableViewModel = koinViewModel()) {
    val navigator = currentComposeNavigator
    val context = LocalContext.current

    var tableName by remember { mutableStateOf("") }
    val columns = remember { mutableStateListOf<ColumnDefinition>() }
    var showAddColumnDialog by remember { mutableStateOf(false) }

    val createState by viewModel.createState.collectAsState()
    val error by viewModel.error.collectAsState()

    LaunchedEffect(createState) {
        if (createState == DataState.Success) {
            Toast.makeText(context, "创建成功", Toast.LENGTH_SHORT).show()
            navigator.navigateUp()
        }
        if (createState == DataState.Error) {
            Toast.makeText(context, "创建失败: $error", Toast.LENGTH_LONG).show()
        }
    }

    Scaffold(
        topBar = {
            AppTopAppBar(title = "创建新数据表", onNavigateUp = { navigator.navigateUp() })
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
        ) {
            OutlinedTextField(
                value = tableName,
                onValueChange = { tableName = it },
                label = { Text("数据表名称") },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true
            )
            Spacer(Modifier.height(16.dp))

            // 字段列表
            Text("字段", style = MaterialTheme.typography.titleMedium)
            LazyColumn(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                items(columns) { col ->
                    ColumnListItem(col, onDelete = { columns.remove(col) })
                }
            }

            Spacer(Modifier.height(8.dp))

            // 添加字段按钮
            Button(
                onClick = { showAddColumnDialog = true },
                modifier = Modifier.fillMaxWidth()
            ) {
                Icon(Icons.Default.Add, contentDescription = null)
                Spacer(Modifier.width(8.dp))
                Text("添加字段")
            }

            Spacer(Modifier.height(16.dp))

            // 创建按钮
            Button(
                onClick = {
                    viewModel.createTable(tableName, columns)
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                enabled = createState != DataState.Loading
            ) {
                if (createState == DataState.Loading) {
                    CircularProgressIndicator(modifier = Modifier.size(24.dp))
                } else {
                    Text("创建数据表")
                }
            }
        }
    }

    if (showAddColumnDialog) {
        AddColumnDialog(
            onDismiss = { showAddColumnDialog = false },
            onConfirm = { colDef ->
                columns.add(colDef)
                showAddColumnDialog = false
            }
        )
    }
}

@Composable
private fun ColumnListItem(col: ColumnDefinition, onDelete: () -> Unit) {
    ListItem(
        headlineContent = { Text(col.name, style = MaterialTheme.typography.titleSmall) },
        supportingContent = {
            Text(col.toSqlString().removePrefix(col.name).trim())
        },
        trailingContent = {
            IconButton(onClick = onDelete) {
                Icon(Icons.Default.Delete, contentDescription = "删除字段", tint = MaterialTheme.colorScheme.error)
            }
        }
    )
    HorizontalDivider()
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun AddColumnDialog(
    onDismiss: () -> Unit,
    onConfirm: (ColumnDefinition) -> Unit
) {
    var name by remember { mutableStateOf("") }
    var type by remember { mutableStateOf(supportedDataTypes.first()) }
    var length by remember { mutableStateOf("") }
    var isPk by remember { mutableStateOf(false) }
    var isAi by remember { mutableStateOf(false) }
    var isNn by remember { mutableStateOf(false) }
    var typeDropdownExpanded by remember { mutableStateOf(false) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("添加新字段") },
        text = {
            LazyColumn { // 使用 LazyColumn 保证在小屏上可滚动
                item {
                    OutlinedTextField(
                        value = name,
                        onValueChange = { name = it },
                        label = { Text("字段名") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Spacer(Modifier.height(8.dp))

                    // 数据类型下拉框
                    ExposedDropdownMenuBox(
                        expanded = typeDropdownExpanded,
                        onExpandedChange = { typeDropdownExpanded = !typeDropdownExpanded }
                    ) {
                        OutlinedTextField(
                            value = type,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("数据类型") },
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = typeDropdownExpanded) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .menuAnchor()
                        )
                        ExposedDropdownMenu(
                            expanded = typeDropdownExpanded,
                            onDismissRequest = { typeDropdownExpanded = false }
                        ) {
                            supportedDataTypes.forEach { dataType ->
                                DropdownMenuItem(
                                    text = { Text(dataType) },
                                    onClick = {
                                        type = dataType
                                        typeDropdownExpanded = false
                                    }
                                )
                            }
                        }
                    }
                    Spacer(Modifier.height(8.dp))

                    OutlinedTextField(
                        value = length,
                        onValueChange = { length = it },
                        label = { Text("长度/值 (可选)") },
                        modifier = Modifier.fillMaxWidth()
                    )
                    Spacer(Modifier.height(8.dp))

                    // 复选框
                    CheckboxRow("主键 (PRIMARY KEY)", isPk) { isPk = it }
                    CheckboxRow("自动递增 (AUTO_INCREMENT)", isAi) { isAi = it }
                    CheckboxRow("不能为空 (NOT NULL)", isNn) { isNn = it }
                }
            }
        },
        confirmButton = {
            Button(onClick = {
                if (name.isNotBlank()) {
                    onConfirm(ColumnDefinition(name, type, length, isPk, isAi, isNn))
                }
            }) { Text("确认") }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) { Text("取消") }
        }
    )
}

@Composable
private fun CheckboxRow(text: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onCheckedChange(!checked) }
    ) {
        Checkbox(checked = checked, onCheckedChange = onCheckedChange)
        Text(text, style = MaterialTheme.typography.bodyMedium)
    }
}